// pages/takePhoto/scanning/scanning.js
const util = require("../../../utils/util");
const app=getApp();

wx.cloud.init({
  env: "自己修改"
})
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    logoUrl: '/images/logo/logo.png', //cloud://cloud1-6g4fn1e1fc689993.636c-cloud1-6g4fn1e1fc689993-1309475441/photos/logo (1).pngscanning Page显示的logo文件的url路径
    // show:true,
    facePhoto:'',
    skinData:{
      age:18,
      gender:"NaN"
    },
    canvasWidth:150,//canvas宽度
    canvasWidth:150,//画布宽度
    lineWidth:153,//线的宽度
    lineHeight:2,//线的高度
    processValue:50,
    facePhotoUrl:'',
    facePhotoBase64:'',
    faceDetectParameter:{
      Access_Token:'',
      requestData:{
        "image": '', //图片内容 base64格式
        "image_type": "BASE64", //图片类型
        "face_field": "age,expression,face_shape,gender,glasses,landmark,landmark150,quality,eye_status,emotion,face_type,mask,spoofing", //请求数据
        "max_face_num": 8, //最大识别人脸数
      } 
    },
    skinAnalyzeInspect:{
      "image": '', //图片内容
      "image_type": "BASE64", //图片类型
      "face_field": "color,smooth,acnespotmole,wrinkle,eyesattr,blackheadpore,skinface,skinquality", //请求数据
      "max_face_num": 1, //最大识别人脸数        
  }

  },

  /**
   * 生命周期函数--监听页面加载
   */

  async onLoad  (options) {

    let that = this;
    let access_token = await db.collection("Settings").doc("bd_face_detect_token").get()
    console.log(access_token)
    //接收传送的数据
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      console.log('图片路径:' + data.imagePath)
      that.setData({
        facePhotoUrl: data.imagePath
      })
      
      //对图片转码
      const fs = wx.getFileSystemManager()
      // 同步接口
      try {
        const res = fs.readFileSync(that.data.facePhotoUrl, 'base64', 0)
        console.log("scanning页成功获取到base64！")

        that.data.facePhotoBase64=res;
        if(app.globalData.hasUserInfo)// 老用户
        {
          // console.log('old用户') ;
          // //判断检测 app.globalData.userInfo.detectAllow
          // if(app.globalData.userInfo.detectAllow){// 检测
          //   console.log('直接检测')
            that.data.faceDetectParameter.requestData.image=res
            that.data.skinAnalyzeInspect.image=res
            that.data.skinAnalyzeInspect.face_field=app.globalData.userInfo.skinAnalyzeInspect//自定义指标
  /*****/ that.getFaceResult(that.data.faceDetectParameter,that.data.skinAnalyzeInspect);
   /*****/ //wx.navigateTo({
  //   url: '/pages/takePhoto/scanning/result/index',
  // })
          // }else{//支付
          //   wx.showToast({
          //     icon:'none',
          //     title: '可用次数不足，请充值后继续！',
          //     duration:3000,
          //     success:()=>{
          //       console.log('前往支付')
          //       // wx.navigateTo({
          //       //   url: 'pay',
          //       // })
          //     }
          //   })
          //   console.log('支付')
          //   //支付完成后，更新全局数据remainingTimes,更新数据库，返回上一页
          // }
        }
        else{
          console.log('new用户')
          //初始化用户数据
          wx.showModal({
            title:'提示',
            content:'请登录后操作',
            success:(res)=>{
              if(res.confirm){
                wx.redirectTo({
                  url: '/pages/person/person',
                })
              }else{
                wx.redirectTo({
                  url: '/pages/home/home',
                })
              }
            }
          })
        }
      } catch(e) {
        console.log('scanning页base64获取失败！')
        that.data.facePhotoBase64 = res;
        //判断余额  
        // if(that.isDetectAllow(db)){

        // }
        //API鉴权
        //人脸检测
        //皮肤分析
        // that.getFaceResult(db, {
        //     Access_Token: '',
        //     requestData: {
        //       "image": res, //图片内容 base64格式
        //       "image_type": "BASE64", //图片类型
        //       "face_field": "age,expression,face_shape,gender,glasses,landmark,landmark150,quality,eye_status,emotion,face_type,mask,spoofing", //请求数据
        //       "max_face_num": 8, //最大识别人脸数
        //     }
        //   }, {
        //     "image": res, //图片内容
        //     "image_type": "BASE64", //图片类型
        //     "face_field": "color,smooth,acnespotmole,wrinkle,eyesattr,blackheadpore,skinface,skinquality", //请求数据
        //     "max_face_num": 1, //最大识别人脸数        
        //   }

        // )
      } 
        // console('scanning页base64获取失败！')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    /**
     *绘制动画
     */
    this.position = {
      x: 1, //线的初始坐标
      y: this.data.canvasWidth + 40,
    }
    // 通过 SelectorQuery 获取 Canvas 节点
    wx.createSelectorQuery()
      .select('#canvas')
      .fields({
        node: true,
        size: true,
      })
      .exec(this.init.bind(this))
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /**
   * 扫描动画
   */
  init(res) {
    const width = res[0].width
    const height = res[0].height

    const canvas = res[0].node
    const ctx = canvas.getContext('2d')

    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)

    const renderLoop = () => {
      this.render(canvas, ctx)
      canvas.requestAnimationFrame(renderLoop)
    }
    canvas.requestAnimationFrame(renderLoop)

    const img = canvas.createImage()
    img.onload = () => {
      this._img = img
    }
    img.src = '/images/检测界面/scan.png'

  },

  render(canvas, ctx) {
    ctx.clearRect(0, 0, this.data.canvasWidth + 5, this.data.canvasWidth + 30)
    this.drawCar(ctx)
  },

  drawCar(ctx) {
    if (!this._img) return
    if (this.position.y < 0) {
      this.position.y = this.data.lineWidth + 40
    }
    ctx.drawImage(this._img, this.position.x, this.position.y -= 1, this.data.lineWidth, this.data.lineHeight)
    ctx.restore()
  },

  /**
   * 百度人脸检测API鉴权并请求人脸识别
   */

  getFaceResult: async function (faceDetectParameter, skinAnalyzeInspect) {
    const that = this; //方便调用本js文件中其他函数
    let key = await db.collection("Settings").doc("bd_face_detect_token").get()
    key = key.data
    // var timestamp = Math.round(Date.parse(new Date()) / 1000); //获取13位当前时间戳，/1000再向上取整，精确到秒
    // var gap = timestamp - key.lastUpdateTime
    // if (gap < key.effictiveTime) { //access_token在有效期内
      //请求人脸检测并对返回结果进行处理
      //console.log(key.Access_Token)
      faceDetectParameter.Access_Token = key.Access_Token; //增加属性Access_Token
      console.log("获取到数据库存放的token:" + faceDetectParameter.Access_Token)
      that.faceDetect(faceDetectParameter, skinAnalyzeInspect);
    // } else { //token超过有效期
    //   //重新获取access_token并请求
    //   that.getAPIgrant(key, faceDetectParameter, skinAnalyzeInspect);
    // }
  },

  /**
   * 人脸检测并反馈结果
   */
  faceDetect: function (faceDetectParameter, skinAnalyzeInspect) {
    let that = this;
    var Access_Token = faceDetectParameter.Access_Token;
    var requestData = faceDetectParameter.requestData;
    // console.log(requestData)
    // console.log(Access_Token)
    // console.log('https://aip.baidubce.com/rest/2.0detect?access_token=' + Access_Token)
    wx.request({
      url: "自己修改" + Access_Token,
      method: "POST",
      data: requestData,
      success: result => {
        console.log("人脸检测结果", result.data)
        // that.dealFaceInfo(result.data.result.face_list[0])
        // 年龄 result.data.result.face_list[0].age;
        // that.setData({
        //   ['skinData.age']:result.data.result.face_list[0].age,
        //   ['skinData.gender']:+result.data.result.face_list[0].gender.type})
        that.data.skinData.age=result.data.result.face_list[0].age;
        that.data.skinData.gender=result.data.result.face_list[0].gender.type;
        var data = result.data;
        if (data.error_code != 0 || data.error_msg != 'SUCCESS') {
          var detail = data.error_msg;
          if (detail == 'pic not has face') detail = '未检测到人脸,请重试';
          wx.showModal({
            title: '失败',
            icon: 'none',
            content: detail,
            showCancel: false,
            success(res) {
              wx.navigateBack({
                delta: 1, //返回1页
              })
            }
          })
        } else if (data.error_code == 0 || data.error_msg == 'SUCCESS') {
          var detail = '';
          if (data.result.face_num > 1) detail += '检测到' + data.result.face_num + '个人脸,';
          if (data.result.face_list[0].face_type.type)
            if (data.result.face_list[0].face_type.type == 'cartoon') detail += '检测到卡通人物,';
          if (data.result.face_list[0].quality.occlusion)
            if (data.result.face_list[0].quality.occlusion > 0.5) detail += '检测到脸部被遮挡,';
          if (data.result.face_list[0].quality.completeness)
            if (data.result.face_list[0].quality.completeness == 0) detail += '人像超出边界,'
          if (data.result.face_list[0].spoofing)
            if (data.result.face_list[0].spoofing > 0.00048) detail += '检测到合成图,非真人相,';
          detail += '请重试!';
          if (detail != ('请重试!')) {
            wx.showModal({
              title: '提示',
              icon: 'none',
              content: detail,
              showCancel: false,
              success(res) {
                wx.navigateBack({
                  delta: 1, //回退一页
                })
              }
            })
          } else {
            // wx.showLoading({
            //   title: '正在分析...',
            // })
            that.skinAnalyze(Access_Token, skinAnalyzeInspect);
            // wx.hideLoading({
            // })
          }
        }
      },
      fail: res => {
        console.log("人脸检测API Access Token请求失败:");
        console.log(res)
      }
    })
  },

  /**
   * 皮肤分析
   */
  skinAnalyze: function (access_token, skinAnalyzeInspect) {
    let that=this;
    wx.request({
      url: '自己修改' + access_token,
      method: "POST",
      data: skinAnalyzeInspect,
      success: result => {
        console.log(result.data)
        if (result.data.error_msg == 'Open api qps request limit reached') {
          wx.showLoading({
            title: '当前服务请求忙...',
            success: function () {
              wx.showModal({
                title: '提示',
                content: '请稍后再试',
                cancelColor: 'cancelColor',
                showCancel: false,
                success: res => {
                  wx.hideLoading({
                    success: (res) => {
                      wx.navigateBack({
                        delta: 1,
                      })
                    },
                  })
                }
              })
            }
          })
        }
        if (result.data.error_code==0) console.log('成功获取到皮肤分析结果!')
        // that.dealFaceInfo(result.data.result.face_list[0])
        // console.log(result.data.result.face_list)
        var skinData=result.data.result.face_list[0]
        skinData.age=that.data.skinData.age
        skinData.gender=that.data.skinData.gender
        // wx.setStorage({
        //   key: 'skinData',
        //   data: skinData,
        //   success: function(res) {
        //     wx.redirectTo({
        //       url: '../scanning/result/index',
        //     })
        //   },
        // })
        wx.navigateTo({
          url: '/pages/takePhoto/scanning/result/index',
          success:res=>{
            res.eventChannel.emit('face_list',{ data:skinData})
          }
        })
      },
      fail: (err) => {
        console.log('皮肤分析出错!')
        console.log(err)
      }
    })
  },
})